package handle;

import Common.SessionManager;
import cn.hutool.json.JSONUtil;
import entity.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import redis.clients.jedis.Jedis;
import utils.RedisPoolUtil;

import java.util.Set;

public class TcpServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
    {
        System.out.println("server receive: " + msg);
        Message m= JSONUtil.toBean(msg,Message.class);
        Channel ch=SessionManager.getSession(m.getTargetId());
        if(ch==null){
            ctx.writeAndFlush("目标未连接");
        }else{
            ctx.writeAndFlush("发送成功");
            ch.writeAndFlush(m.getContent());
        }
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel ch=ctx.channel();
        System.out.println("Client connected: " + ctx.channel().remoteAddress());
        System.out.println("id:"+ch.id().asShortText());
        SessionManager.addSession(ch.id().asShortText(),ch);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client disconnected: " + ctx.channel().remoteAddress());
        SessionManager.removeByChannel(ctx.channel());
    }
}
